
import html2canvas from "html2canvas"
import JsPDF from 'jspdf'
/**
 * 导出报告
 * @param {*} flag 1 pdf/ 0 png
 * @param {*} refDom 容器的ref
 * @param {*} name 文件名
 */
export function onExport(flag, refDom, name) {
  const clientWidth = refDom.offsetWidth
  const clientHeight = refDom.offsetHeight
  const kh = [clientWidth, clientHeight]
  html2canvas(refDom, { useCORS: true, logging: true }).then((canvas) => {
    var pageData = canvas.toDataURL('image/jpeg', 1.0)
    if (flag) {
      var contentWidth = canvas.width
      var contentHeight = canvas.height
      var pageHeight = contentWidth / 592.28 * 841.89
      var leftHeight = contentHeight
      var position = 0
      var imgWidth = 595.28
      var imgHeight = 595.28 / contentWidth * contentHeight
      var pdf = new JsPDF('', 'pt', 'a4')
      if (leftHeight < pageHeight) {
        pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
      } else {
        // 分页
        while (leftHeight > 0) {
          pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
          leftHeight -= pageHeight
          position -= 841.89
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage()
          }
        }
      }
      // 可动态生成
      pdf.save(name)
    } else {
      downloadPNG(pageData, kh, name)
    }
  })
}
// 下载图片
function downloadPNG(imgUrl, kh, name) {
  getUrlBase64(imgUrl, kh).then((base64) => {
    const link = document.createElement('a')
    link.href = base64
    link.download = `${name}.png`
    link.click()
  })
}
// 设置
function getUrlBase64(url, kh) {
  return new Promise((resolve) => {
    let canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.crossOrigin = 'Anonymous' // 允许跨域
    img.src = url
    img.onload = () => {
      canvas.height = kh[1]
      canvas.width = kh[0]
      ctx.drawImage(img, 0, 0, kh[0], kh[1])
      const dataURL = canvas.toDataURL('image/png')
      canvas = null
      resolve(dataURL)
    }
  })
}